/**
 *   This file is part of Java Simple Sampler.
 *
 *   Java Simple Sampler is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License.
 *
 *   Java Simple Sampler is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Java Simple Sampler.  If not, see <http://www.gnu.org/licenses/>.
 *
 *   @author David Lapetina	
 */
package net.onirik.mao.sampler.midi;

import java.util.HashMap;
import java.util.Map;

import javax.sound.midi.MidiMessage;
import javax.sound.midi.Receiver;
import javax.sound.midi.ShortMessage;

import net.onirik.mao.sampler.sound.SamplePlayer;
import net.onirik.mao.sampler.sound.SamplePlayerMap;

/**
 * This class is the main Midi Receiver. Its purpose is to dispatch all midi
 * event to the MidiListeners.
 * 
 * @author david
 */
public class JSSMidiReceiver implements Receiver {

	private final Map samplePlayersMapByChannels = new HashMap();

	public JSSMidiReceiver() {
		for (int i = 0; i < 16; i++) {
			samplePlayersMapByChannels.put(new Integer(i),
					new SamplePlayerMap());
		}
	}

	public void close() {
	}

	public SamplePlayerMap getSamplePlayerMap(int channel) {
		return (SamplePlayerMap) samplePlayersMapByChannels.get(new Integer(
				channel));
	}

	public void send(MidiMessage msg, long arg1) {
		//System.out.println("Received message " + msg);
		if (ShortMessage.class.isInstance(msg)) {
			ShortMessage message = (ShortMessage) msg;
			int channel = message.getChannel();
			//System.out.println("channel " + channel);
			int command = message.getCommand();
			int data1 = message.getData1();
			// int data2 = message.getData2();
			// int status = message.getStatus();
			//System.out.println("command " + command);
			SamplePlayer samplePlayer = getSamplePlayerMap(channel)
					.getSamplePlayer(data1, true);
			switch (command) {
			case ShortMessage.NOTE_ON:
				if (samplePlayer != null) {
					play(samplePlayer);
				}
				break;
			case ShortMessage.NOTE_OFF:
				if (samplePlayer != null) {
					samplePlayer.stop();
				}
				break;
			}
		}
	}

	private void play(final SamplePlayer player) {
		new Thread() {
			public void run() {
				player.play();
			}
		}.start();
	}
}